import "dart:ffi";

import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/bill/api.dart";
import "package:ct_pa_majordomo/pages/check_in_detail/check_in_info_state.dart";
import "package:ct_pa_majordomo/pages/check_in_detail/complete/widgets/bill_detail/index.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/utils/date_tools.dart";
import "package:ct_pa_majordomo/utils/index.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/divider/solid_divider.dart";
import "package:ct_pa_majordomo/widgets/empty_data/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";

class Complete extends StatefulWidget {
  const Complete({super.key});

  @override
  State<StatefulWidget> createState() => _CompleteState();

}

class _CompleteState extends State<Complete> {

  List _list = [];
  int _total = 0;
  double _expensesTotalMoney = 0;
  double _incomeTotalMoney = 0;
  Map<String, dynamic> _params = {
    "pageSize": 10,
    "pageNum": 1,
    "status": 2,
    "checkInId": null
  };

  void _getCompleteList() async {
    Map resData = await billApi.getBillList(_params);
    List data = resData["data"]["rows"] ?? [];
    setState(() {
      _list.addAll(data);
      _total = resData["data"]["total"] ?? 0;
      _expensesTotalMoney = Utils.toDouble(resData["data"]["expensesTotalMoney"]);
      _incomeTotalMoney = Utils.toDouble(resData["data"]["incomeTotalMoney"]);
      print("ssss:>>> $_total");
      print("ssss:>>> $data");
    });
  }

  Future<void> _refresh() async {
    _params["pageNum"] = 1;
    _list = [];
    _getCompleteList();
  }

  Widget _render() {
    return Column(
      children: <Widget>[
        Padding(
          padding: EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage, vertical: 12),
          child: Row(
            children: [
              Text("收入：${Utils.formatCurrency(_incomeTotalMoney)}", style: TextStyle(fontSize: 14, color: ThemeVars.colorSuccess),),
              SizedBox(width: 20,),
              Text("支出：${Utils.formatCurrency(_expensesTotalMoney)}", style: TextStyle(fontSize: 14, color: ThemeVars.colorError),),
            ],
          ),
        ),
        const SolidDivider(),
        Padding(
          padding: EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage),
          child: Column(
            children: List.generate(_list.length * 2 - 1, (index) {
              if (index.isOdd) {
                return const SolidDivider();
              }
              Map item = _list[index ~/ 2];
              return GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  Navigator.push(context, CupertinoPageRoute(builder: (BuildContext context) {
                    return BillDetail(info: item,);
                  }));
                },
                child: Padding(
                  padding: EdgeInsets.symmetric(vertical: 12),
                  child: Column(
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(item["name"] ?? "--", style: TextStyle(fontSize: 16),),
                          Text(
                            "${item["inoutFlag"] == "1" ? "+" : "-"}${Utils.formatCurrency(item["money"])}",
                            style: TextStyle(color: item["inoutFlag"] == "1" ? ThemeVars.colorSuccess : ThemeVars.colorError),
                          )
                        ],
                      ),
                      SizedBox(height: 4,),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text("2024-08-01", style: TextStyle(fontSize: 14, color: ThemeVars.colorTextTer),),
                          Text("${DateTools.formatYMD(item["updateTime"])}", style: TextStyle(fontSize: 14),)
                        ],
                      )
                    ],
                  ),
                ),
              );
            }),
          ),
        ),
      ],
    );
  }

  @override
  void didChangeDependencies() {
    _params["checkInId"] = CheckInInfoState.of(context)?.info["checkInId"];
    _getCompleteList();
    super.didChangeDependencies();
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      top: false,
      bottom: false,
      child: Stack(
        children: [
          Builder(
            builder: (BuildContext context) {
              return RefreshIndicator(
                onRefresh: _refresh,
                child: CustomScrollView(
                  key: PageStorageKey<String>("完成账单"),
                  slivers: <Widget>[
                    SliverOverlapInjector(
                      // This is the flip side of the SliverOverlapAbsorber
                      // above.
                      handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
                    ),
                    SliverPadding(
                        padding: const EdgeInsets.only(bottom: 72),
                        sliver: SliverToBoxAdapter(
                            child: Container(
                              decoration: const BoxDecoration(
                                color: Colors.white,
                              ),
                              child: _list.length == 0
                                  ? EmptyData()
                                  : _render(),
                            )
                        )
                    ),
                  ],
                ),
              );
            },
          ),
          Positioned(
            bottom: 0,
            left: 0,
            width: MediaQuery.of(context).size.width,
            child: Container(
              padding: const EdgeInsets.all(ThemeVars.paddingPage),
              decoration: const BoxDecoration(
                color: ThemeVars.colorBackground,
              ),
              child: Button(
                type: ButtonType.primary,
                onPressed: () {
                  Stacker.pushNamed(Keys.CHECK_IN_DETAIL_BILL_ACCOUNTING_ADD);
                },
                child: const Text("添加记账")
              ),
            )
          ),
        ],
      )
    );
  }

}